class WeeklyResultWorksSyn < ActiveRecord::Migration
  def self.up
    fresult = WeeklyResult.first :conditions => "weekly_result_work_id is null", :order => "id"
    if fresult
    fid = fresult.id - 1
    puts time = Time.now
    while true do
      results = WeeklyResult.all :offset => fid, :limit => 2500, :order => "id"
      works = WeeklyResultWork.all :conditions => ["wid in (?)", results.collect(&:wid)], :order => "id desc"
	    break if results.empty?
      puts "get #{results.first.id} to #{results.last.id}. use #{Time.now - time} sec."
      WeeklyResult.transaction do
        results.each do |result|
          wrw = works.detect{|w| w.wid == result.wid}
          unless wrw && result.name == wrw.name && result.wtype == wrw.wtype && result.author == wrw.author
            wrw = WeeklyResultWork.create :wid => result.wid, :name => result.name, :wtype => result.wtype, :author => result.author
          end
          result.weekly_result_work_id = wrw.id
          result.wid = nil
          result.save!
        end
      end
      fid += 2500
    end
    end
  end

  def self.down
  end
end
